package zuk.clipvietfun.likeandhistory;

import java.util.ArrayList;
import java.util.List;

import zuk.clipvietfun.ApiYoutube;
import zuk.clipvietfun.R;
import zuk.clipvietfun.clip.Clip;
import zuk.clipvietfun.clip.ClipAdapterAllList;
import zuk.clipvietfun.getdata.SetList;
import zuk.clipvietfun.plus.PopupAllList;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
@SuppressLint("ValidFragment")
public class FragmentLike extends ListFragment {
	ClipAdapterAllList adapter;
	List<Clip> listClips = new ArrayList<Clip>();
	PopupWindow popupWindow;
	ListView lv;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		setNewListAdapter();
		return inflater.inflate(R.layout.fragment_clip, null);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		lv = getListView();
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int pos, long arg3) {
				try {
					new PopupAllList(listClips,pos,getActivity(),adapter,adapter.getView(pos, arg1, arg0),lv).showPopup();
					adapter.notifyDataSetChanged();
				} catch (Exception e) {
				}
				return true;
			}
		});
		super.onActivityCreated(savedInstanceState);
	}
	public void setNewListAdapter() {
		listClips = new SetList(getActivity()).setlist();
		if (listClips != null) {
			adapter = new ClipAdapterAllList(getActivity(), R.layout.clip, listClips);
			setListAdapter(adapter);
		} else {
			Toast.makeText(getActivity(), "Error 503 or 404",Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		Clip video = listClips.get(position);
		if (video == null) {
			Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
		}
		new History(getActivity()).addHistory(video,false);
		watchVideo(video.getuTube());
		super.onListItemClick(l, v, position, id);
	}

	private void watchVideo(String video) {
		Intent i = new Intent(getActivity(), ApiYoutube.class);
		i.putExtra("key", video);
		startActivity(i);
	}

	@Override
	public void onResume() {
		adapter.notifyDataSetChanged();
		super.onResume();
	}
	
}
